package com.stylefeng.guns.core.util.excel;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * excel导入组件 .xlsx后缀
 *
 * @author carloszhang
 */
public abstract class AnalyzeExcelXlsxComponent<T> {

    private static final int DEFAULT_ONSET_ROW = 1;

    private static final int DEFAULT_VALUE = 0;

    public List<T> analyzeExcel(InputStream is) throws Exception {
        return analyzeExcel(is, DEFAULT_ONSET_ROW);
    }

    public List<T> analyzeExcel(InputStream is, int onsetRow) throws Exception {

        XSSFWorkbook workbook = new XSSFWorkbook(is);
        List<T> datas = new ArrayList<T>();
        XSSFSheet sheet = workbook.getSheetAt(DEFAULT_VALUE);
        if (sheet == null) {
            return null;
        }
        for (int rowNum = onsetRow; rowNum <= sheet.getLastRowNum(); rowNum++) {
            XSSFRow row = sheet.getRow(rowNum);
            if (row == null || StringUtils.isBlank(String.valueOf(row.getCell(DEFAULT_VALUE)))) {
                continue;
            }
            datas.add(buildData(row));
        }
        return datas;

    }

    protected abstract T buildData(XSSFRow row);

    protected XSSFCell getCell(XSSFRow row, int onsetCell) {
        return row.getCell(onsetCell);
    }

    protected String getValue(XSSFCell cell) {
        try {
            return StringUtils.trimToNull(String.valueOf(cell.getStringCellValue()));
        } catch (Exception e) {
            return StringUtils.trimToNull(String.valueOf(new BigDecimal(cell.getNumericCellValue()).intValue()));
        }

    }


    protected String getValueNum(XSSFCell cell) {
        return StringUtils.trimToNull(String.valueOf(cell.getNumericCellValue()));
    }
}
